package com.glc.hms.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glc.hms.common.util.JWTUtil;
import com.glc.hms.config.TokenProperties;
import com.glc.hms.system.dao.SysUserTokenMapper;
import com.glc.hms.system.entity.SysUser;
import com.glc.hms.system.entity.SysUserToken;
import com.glc.hms.system.service.ISysUserTokenService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统用户Token 服务实现类
 * </p>
 *
 * @author Santa
 * @since 2019-11-14
 */
@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken> implements ISysUserTokenService {

    @Autowired
    private TokenProperties tokenProperties;
    @Autowired
    private SysUserTokenMapper userTokenMapper;


    /**
     * 根据id查询token
     * @param userId
     * @return
     */
    public SysUserToken queryByUserId(Long userId){
        QueryWrapper<SysUserToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        SysUserToken sysUserToken = userTokenMapper.selectOne(queryWrapper);
        return sysUserToken;
    }

    /**
     * 根据token查询
     * @param token
     * @return
     */
    public SysUserToken queryByToken(String token){
        QueryWrapper<SysUserToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token",token);
        return userTokenMapper.selectById(queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> creatToken(Long userId) {

        //半小时后过期
        int refreshTime = tokenProperties.getRefreshTime();
        int EXPIRE = 60 * refreshTime;

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        // 生成Token
        String uuid = IdUtil.simpleUUID();

        int validTime = tokenProperties.getValidTime();
        long ttl = validTime * 60 * 1000;
        Map<String, Object> claims = new HashMap<>();
        //TODO 此处应该把用户信息存redis  后期实现
        //  claims.put(UserInfoKey,roleRightStr);
        String userGuid = String.valueOf(userId);
        String jwt = JWTUtil.createJWT(uuid, userGuid,ttl,claims);



        //判断是否生成过token
        SysUserToken tokenEntity = queryByUserId(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(jwt);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            userTokenMapper.insert(tokenEntity);
        }else{
            tokenEntity.setToken(jwt);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
            QueryWrapper<SysUserToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",tokenEntity.getUserId());
            userTokenMapper.update(tokenEntity,queryWrapper);
        }

        Map<String, Object> map = Maps.newHashMap();
        map.put("token",jwt);
        return map;
    }
}
